package com.anyext.storage.dialect;

public class MySQL5Dialect implements Dialect {

	@Override
	public String getLimitSql(String sql, int offset, int limit) {
		sql = sql.trim();
		String lowerSql = sql.toLowerCase();

		boolean isForUpdate = false;

		if (lowerSql.endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		}

		StringBuffer sb = new StringBuffer(sql.length() + 16);

		sb.append(sql);

		if (offset <= 1) {
			if (limit < Integer.MAX_VALUE) {
				sb.append(" limit ").append(limit);
			}
		} else {
			sb.append(" limit ").append((offset - 1)).append(", ").append(limit);
		}

		if (isForUpdate) {
			sb.append(" for update");
		}
		return sb.toString();
	}

}
